package com.teamclub.erp.sservices

import java.util.Map

import io.ebean.{Ebean, ExpressionList}
import com.google.common.collect.Maps
import com.teamclub.domain.erp.product.ProductInfo
import com.teamclub.erp.sforms.ProductInfoForm
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.BeanUtils
import org.springframework.stereotype.Service

import scala.collection.JavaConversions._

/**
  * Created by ilkkzm on 17-9-11.
  */

@Service
class ProductListService {
  def listArray: Map[String, String] = {
    Maps.newHashMap()
  }

  private def expr(where: ExpressionList[ProductInfo], form: ProductInfoForm): Unit = {
    if(StringUtils.isNotBlank(form.organNo)) {
      where.eq("organNo", form.organNo)
    }
    if(StringUtils.isNotBlank(form.productName)) {
      where.like("productName", "%" + form.productName + "%")
    }
    where.eq("isDelete", 0)
    where.orderBy("createdTime desc")
  }

  def list(form: ProductInfoForm): F.Either[Pager[ProductInfo], ErrorCode] = {
    var where = Ebean.find(classOf[ProductInfo]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: ProductInfoForm): F.Either[ProductInfo, ErrorCode] = {
    var instance = new ProductInfo
    if(form.id != null) {
      instance = Ebean.find(classOf[ProductInfo], form.id)
    }
    if(instance == null) {
      return F.Either.Right(ErrorCode.BIZ_FAILURE)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.id != null) {
      instance.update()
    } else {
      instance.setIsDelete(false)
      instance.save()
    }
    F.Either.Left(instance)
  }

  def del(form: ProductInfoForm): F.Either[ProductInfo, ErrorCode] = {
    if(form.id == null) {
      return F.Either.Right(ErrorCode.ENTITY_NOT_FOUND)
    } else {
      val instance = Ebean.find(classOf[ProductInfo], form.id)
      instance.setIsDelete(true)
      instance.update()
      F.Either.Left(instance)
    }
  }

}
